﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mapenect.GesturePatterns;
using System.Threading;
using Mapenect.Data;
using System.Diagnostics;

namespace Mapenect.GestureInterpreter
{
    abstract class Interpreter
    {
        protected float threshold;
        protected Gesture pattern;
        protected DataContainer jointData;
        
        internal delegate void GestureEventhandler(Object sender, EventArgs e);
        public event GestureEventhandler GestureDetected;

        private Thread gestureDetectionThread;
        private bool shouldRun = false;

        public long elapsedMilliSeconds { get; private set; }

        public Interpreter(DataContainer jointData, Gesture pattern = null, float threshold = 0)
        {
            this.threshold = threshold;
            this.pattern = pattern;
            this.jointData = jointData;
        }

        public void Start()
        {
            shouldRun = true;
            gestureDetectionThread = new Thread(RunGestureDetectionThread);
            gestureDetectionThread.Start();
        }

        public void Stop()
        {
            if (shouldRun)
            {
                shouldRun = false;
                gestureDetectionThread.Join();
                gestureDetectionThread = null;
            }
        }

        private void RunGestureDetectionThread()
        {
            bool gestureDetected;
            Stopwatch watch = new Stopwatch();
            Thread.Sleep(2000);
            while (shouldRun)
            {
                watch.Start();
                gestureDetected = checkForGesture();
                watch.Stop();


                if (gestureDetected)
                    GestureDetected(this, new EventArgs());

                elapsedMilliSeconds = watch.ElapsedMilliseconds;
                watch.Reset();
                Thread.Sleep(50);

            }
        }

        abstract protected bool checkForGesture();

    }
}
